package com.siro.auth.base.config;

import com.siro.auth.base.security.filter.JwtAuthenticationTokenFilter;
import com.siro.auth.base.security.handler.AuthenticationEntryPointHandler;
import com.siro.auth.base.security.handler.CustomerAccessDeniedHandler;
import com.siro.auth.base.security.handler.LoginFailureHandler;
import com.siro.auth.base.security.handler.LoginSuccessHandler;
import com.siro.auth.base.security.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 配置类
 *
 * @author starsea
 * @date 2022-07-13 17:14
 */
@Configuration
@EnableWebSecurity
//开启权限注解控制
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * 登录认证成功处理器
     */
    @Autowired
    private LoginSuccessHandler loginSuccessHandler;

    /**
     * 用户认证失败处理器
     */
    @Autowired
    private LoginFailureHandler loginFailureHandler;

    /**
     * 自定义授权过程中的异常
     */
    @Autowired
    private CustomerAccessDeniedHandler accessDeniedHandler;

    /**
     * 自定义认证异常类
     */
    @Autowired
    private AuthenticationEntryPointHandler authenticationEntryPointHandler;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 处理登录认证
     *
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.formLogin()
                //必须使用post请求
                .loginProcessingUrl("/api/user/login")
                //设置登录验证成功跳转地址
                .successHandler(loginSuccessHandler)
                //设置登录验证失败跳转地址
                .failureHandler(loginFailureHandler)
                // CSRF禁用，因为不使用session
                .and().csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 验证码captchaImage 允许匿名访问
                .antMatchers("/api/user/login").anonymous()
                // 静态资源，可匿名访问
                .antMatchers(
                        "/swagger-ui.html",
                        "/swagger-ui/*",
                        "/swagger-resources/**",
                        "/v2/api-docs",
                        "/webjars/**",
                        "/configuration/ui",
                        "/configuration/security"
                ).anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and().exceptionHandling()
                // 认证失败处理类
                .authenticationEntryPoint(authenticationEntryPointHandler)
                // 授权失败处理类
                .accessDeniedHandler(accessDeniedHandler)
                // 允许跨域访问
                .and().cors();

        //把token校验过滤器添加到过滤器链中
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 配置身份认证接口
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 加密操作
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
